package cqut.wys.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/eventQueue")
public class EventQueueController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/add")
    public String add() {
        String sql;
        for (int i = 0; i < 100; i++) {
            int topic = new Random().nextInt(4);
            String data = "我是消息" + i;
            int uid = new Random().nextInt(10);
            sql = "INSERT INTO `queue`.`t_event_queue` (`topic`, `status`, `data`, `uid`, " +
                    "`create_date`) VALUES (" + topic + ",0 ,'"+data+"' ," + uid+",'"+ LocalDateTime.now() +"')";
            System.out.println(sql);
            jdbcTemplate.execute(sql);
        }
        return "aaa";
    }

    @GetMapping("/update")
    public String update() {
        new Thread(() -> {
            while (true) {
                new Thread(() -> {
                    jdbcTemplate.execute("UPDATE t_event_queue SET `status`=1, qid=LAST_INSERT_ID(qid),uid=10 WHERE `status`=0 limit 1");
                    List<Map<String, Object>> map = jdbcTemplate.queryForList("SELECT * FROM t_event_queue WHERE ROW_COUNT()>0 and qid=LAST_INSERT_ID()");
                    System.out.println(map);
                }).start();
                new Thread(() -> {
                    jdbcTemplate.execute("UPDATE t_event_queue SET `status`=1, qid=LAST_INSERT_ID(qid),uid=11 WHERE `status`=0 limit 1");
                    List<Map<String, Object>> map = jdbcTemplate.queryForList("SELECT * FROM t_event_queue WHERE ROW_COUNT()>0 and qid=LAST_INSERT_ID()");
                    System.out.println(map);
                }).start();
                new Thread(() -> {
                    jdbcTemplate.execute("UPDATE t_event_queue SET `status`=1, qid=LAST_INSERT_ID(qid),uid=12 WHERE `status`=0 limit 1");
                    List<Map<String, Object>> map = jdbcTemplate.queryForList("SELECT * FROM t_event_queue WHERE ROW_COUNT()>0 and qid=LAST_INSERT_ID()");
                    System.out.println(map);
                }).start();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        UPDATE targets, (SELECT id FROM targets WHERE status='C' AND schedule<CURRENT_TIMESTAMP ORDER BY schedule ASC LIMIT 1) tmp SET status='D' WHERE targets.id=LAST_INSERT_ID(tmp.id);
//        SELECT * FROM targets WHERE ROW_COUNT()>0 and id=LAST_INSERT_ID();
        return "bbb";
    }
}
